package com.runvp.common.hex;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 公用处理器工具类
 *
 * @author xkk
 * @date 2020/12/16
 */
@Slf4j
public class CommonHandleUtils {


    /**
     * 构建sn 数组
     *
     * @param sn
     * @return byte[]
     */
    public static byte[] buildSn(String sn) {
        byte[] bytes = new byte[sn.length() / 2];
        for (int i = 0; i < sn.length() / 2; i++) {
            bytes[i] = (byte) Integer.parseInt(sn.substring(i * 2, i * 2 + 2));
        }
        return bytes;
    }

    /**
     * 构建 数字 数组
     *
     * @param numData
     * @return byte[]
     */
    public static byte[] buildNumByte(String numData) {
        if(StringUtils.isBlank(numData)){
            return null;
        }
        byte[] bytes = new byte[numData.length() / 2];
        for (int i = 0; i < numData.length() / 2; i++) {
            bytes[i] = (byte) Integer.parseInt(HexConvert.hexNumber2Ten(numData.substring(i * 2, i * 2 + 2)));
        }
        return bytes;
    }

    public static String toString(String numData) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numData.length() / 2; i++) {
            sb.append(HexConvert.hexNumber2Ten(numData.substring(i * 2, i * 2 + 2)));
        }
        return sb.toString();
    }
    /**
     * 按照规则截取
     * @param result
     * @param section
     * @return str
     */
    public static String substrByRule(String result,int[] section ){
        if(StringUtils.isBlank(result)){
            log.warn("报文为空");
            return "";
        }
        if(section.length < 1){
            log.warn("截取规则不合法");
            return "";
        }
//        log.info("本次截取【{}】",section[0]+"-"+section[1]);
        if(result.length() < section[1]){
            log.warn("截取规则超出报文长度");
            return "";
        }
        try {
            return result.substring(section[0],section[1]);
        }catch (Exception e){
            log.error("截取【{}】异常:{}",section[0]+"-"+section[1],e);
            return "";
        }
    }



}
